<template>
  <div class="container">
    <!-- <Row :gutter="50">
      <i-Col span="6" style="min-width:61px;"> -->
    <Layout>
      <Sider
        hide-trigger
        style="margin-right: 50px; min-width: 240px; background-color: #fff"
      >
        <div class="left">
          <div class="head">
            <span>
              <Icon type="ios-list-box" size="16" />
              <span>标签分类</span>
              <Icon
                type="md-add"
                v-if="Validation.check(Resources.BANNERS)"
                @click="handleAdd"
                size="20"
              />
            </span>
          </div>
          <div class="tree-box">
            <div
              style="font-size: 14px; padding: 5px 10px"
              @click="getAllResult"
              :class="{ 'active-menu': AllSort === true }"
            >
              <Icon type="ios-folder-open-outline" size="20" />
              <label>全部</label>
            </div>
            <div
              class="tree-menu"
              v-for="(item, index) in bloc.sortPage.items"
              :key="item.labelsortId"
              :class="{
                'active-menu':
                  item.labelsortId === bloc.sortLabel.labelsortId && AllSort === false,
              }"
              @click="selectCurrentMenu(item, index)"
              @mouseenter="mouseMenuItem = item.labelsortId"
              @mouseleave="mouseMenuItem = -1"
            >
              <Icon type="ios-folder-open-outline" size="20" />
              <label>{{ item.labelsortname }}</label>
              <transition name="fade">
                <span style="width: 70px" v-if="mouseMenuItem === item.labelsortId">
                  <Icon
                    :type="icon"
                    v-for="icon in menuIcons"
                    :key="icon"
                    @click.stop="handleSort(icon, item)"
                    color="#666"
                    size="16"
                  />
                </span>
              </transition>
            </div>
          </div>
        </div>
      </Sider>

      <Content>


        <div class="right">
          <ul>
            <Row>
              <div class="toolbar">
                <Button
                  type="primary"
                  icon="md-add"
                  style="margin-right: 30px"
                  @click="addItem()"
                  v-if="Validation.check(Resources.LABEL_SORT_ADD)"
                >新增标签
                </Button>
                <!--              <Select v-model="bloc.model.id" style="width:200px;margin-right:5px" placeholder="设备型号">-->
                <!--                <Option v-for="item in bloc.modelPage.items" :key="item.id" :value="item.id">-->
                <!--                  {{ item.modelName }}-->
                <!--                </Option>-->
                <!--              </Select>-->
                <Input
                  placeholder="标签名称"
                  v-model="bloc.model.labelname"
                  style="width: 180px; margin-right: 10px"
                  type="text"
                />
                <CompanySeletorSingle :companyId="bloc.model.companyId" style=" width: 180px;margin-right:10px"
                                      @on-change="(value) => (bloc.model.companyId = value)"
                                      v-if="Validation.isRootCompany"></CompanySeletorSingle>
                <Button
                  icon="ios-search"
                  type="primary"
                  style="margin-left: 5px; margin-right: 5px"
                  @click="
                    bloc.getLabels(
                      bloc.LabelPage.pageIndex,
                      bloc.LabelPage.pageSize,
                      'DESC',
                      bloc.model.labelsortId,
                      bloc.model.companyId,
                      bloc.model.labelname
                    )
                  "
                >
                  查询
                </Button>
                <Button icon="md-refresh" @click="reset">重置</Button>
              </div>
            </Row>
          </ul>
          <div>
            <Table
              border
              ref="selection"
              :columns="columns"
              :data="bloc.LabelPage.items"
            >
              <template slot-scope="{ row, index }" slot="action">
                <div style="white-space: nowrap">
                  <Button
                    size="small"
                    style="margin-left: 5px; margin-right: 5px"
                    @click="editItem(row)"
                    type="info"
                    v-if="Validation.check(Resources.LABEL_SORT_UPDATE)"
                  >
                    编辑
                  </Button>
                  <Button
                    size="small"
                    style="margin-left: 5px; margin-right: 5px"
                    @click="toRemoveItem(row)"
                    v-if="Validation.check(Resources.LABEL_SORT_DELETE)"
                    type="warning"
                  >删除
                  </Button>
                </div>
              </template>
              <slot name="footer" slot="footer">
                <Page
                  show-elevator
                  show-total
                  show-sizer
                  :total="bloc.LabelPage.itemCount"
                  :current="bloc.LabelPage.pageIndex"
                  :page-size="bloc.LabelPage.pageSize"
                  :page-size-opts="[15, 30, 50, 100]"
                  @on-change="changepages"
                  @on-page-size-change="changepagesize"
                />
              </slot>
            </Table>
          </div>
        </div>
      </Content>
      <!-- </i-Col> -->

      <Modal
        title="新增标签"
        v-model="addLabel"
        class-name="vertical-center-modal"
        @on-cancel="cancel"
      >
        <p slot="header">
          <span>新增标签</span>
        </p>
        <div style="text-align: center">
          <Form
            ref="sort"
            :model="sort"
            :rules="ruleValidate"
            label-position="right"
            :label-width="100"
          >
            <FormItem label="标签分类:" prop="labelsortname" required>
              <Input v-model="sort.labelsortname" :maxlength="5" />
            </FormItem>
          </Form>
        </div>
        <div slot="footer">
          <AppButton
            ref="save"
            type="primary"
            @click="addSort(sort.labelsortname.trim())"
          >确定</AppButton
          >
        </div>
      </Modal>

      <Modal
        title="编辑设备分类"
        v-model="edit"
        class-name="vertical-center-modal"
        @on-cancel="cancel"
      >
        <p slot="header">
          <span>编辑标签分类</span>
        </p>
        <div style="text-align: center">
          <Form
            ref="editSort"
            :model="sort1"
            :rules="ruleValidate1"
            label-position="right"
            :label-width="100"
          >
            <FormItem label="分类名称:" prop="labelsortname1">
              <Input v-model="sort1.labelsortname1" :maxlength="5" />
            </FormItem>
          </Form>
        </div>
        <div slot="footer">
          <AppButton
            ref="edit"
            type="primary"
            @click="editSorts(sort1.id, sort1.labelsortname1.trim())"
          >确定</AppButton
          >
        </div>
      </Modal>
    </Layout>
    <Modal
      title="确认提示"
      v-model="sortDelete"
      class-name="vertical-center-modal"
      @on-ok="handleDelete(bloc.model.labelsortId)"
    >
    </Modal>


  </div>
</template>
<script lang="ts">
    import { Component, Vue } from "vue-property-decorator";
    import { LabelBloc } from "./LabelBloc";
    import { Label } from "@/base/model/Label";
    import { LabelSort } from "@/base/model/LabelSort";
    import { Route } from "vue-router";
    import CompanySeletorSingle from "@/component/CompanySeletorSingle.vue";
    import { Validation } from "@/base/Validation";
    import { Resources } from "@/base/Resources";
    import { AppButton } from "@/type/AppButton";
    import { formatDate } from '@/base/util/Dates';

    const getColumns = (bloc: LabelBloc) => [

        {
            title: "标签分类",
            width: 100,
            render: (h: any, params: any) => {
                return h("span", {
                    domProps: {
                        innerText: bloc.getsortName(params.row.labelsortId),
                    },
                });
            },
            align: "left",
            tooltip: true,
        },
        {
            title: "标签名称",
            width: 100,
            render: (h: any, params: any) => {
                return h("span", {
                    domProps: {
                        innerText: params.row.labelname,
                    },
                });
            },
            align: "left",
            tooltip: true,
        },
        {
            title: "所属品牌商",
            render: (h: any, params: any) => {
                return h("span", {
                    domProps: {
                        innerText: bloc.getCompanyName(params.row.companyId),
                    },
                });
            },
            align: "left",
            minWidth: 220,
            ellipsis: true,
            tooltip: true,
        },
        {
            title: "排序",
            key: "sort",
            align: "left",
            minWidth: 100,
            tooltip: true,
        },
        {
            title: "最后修改时间",
            render: (h: any, params: any) => {
                return h("span", {
                    domProps: {
                        innerText: formatDate(
                            new Date(params.row.updatetime),
                            "yyyy-MM-dd hh:mm:ss"
                        ),
                    },
                });
            },
            width: 160,
            align: "left",
            tooltip: true,
        },
        {
            title: "操作",
            key: "action",
            width: 47 * 2 + 61 * 0 + 75 * 0 + 20,
            align: "left",
            slot: "action",
            fixed: "right",
        },
    ];
    @Component({
        components: { CompanySeletorSingle },
    })
    export default class extends Vue {
        Validation = Validation;
        Resources = Resources;
        bloc: LabelBloc = new LabelBloc();
        AllSort: boolean = false;
        sortDelete: boolean = false;
        modelDelete: boolean = false;
        mouseMenuItem = -1;
        columns = getColumns(this.bloc);

        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next((vm) => {
                vm.bloc.sortLabel.labelsortId = Number(vm.$route.query.labelsortId) || undefined;
                if (!vm.bloc.sortLabel.labelsortId) {
                    vm.AllSort = true;
                }
                vm.initTreeList();
                vm.bloc.getCompanyList(vm.bloc.company.pageIndex, 500, "DESC");
            });
        }

        ruleValidate = {
            labelsortname: [
                { required: true, message: "分类名称不能为空", trigger: "blur" },
            ],
        };
        ruleValidate1 = {
            labelsortname1: [
                { required: true, message: "分类名称不能为空", trigger: "blur" },
            ],
        };
        getAllResult() {
            this.AllSort = true;
            this.$router.push({ path: '/label' });
            delete this.bloc.sortLabel.labelsortId;
            this.bloc
                .getLabels(
                    this.bloc.LabelPage.pageIndex,
                    this.bloc.LabelPage.pageSize,
                    "DESC",
                    undefined,
                    undefined,
                    undefined
                )
                .then((res) => {
                    this.bloc.getAllSort(1, 1000, "ASC");
                });
        }
        //
        add = false;
        edit: any = false;
        addLabel: any = false;
        sort: any = {
            id: 0,
            labelsortname: "",
        };
        sort1: any = {
            id: 0,
            labelsortname1: "",
        };
        //
        // menuIconList: string[] = ['md-create', 'md-trash', 'md-arrow-down'];
        //
        menuIconList = [
            {
                name: "md-create",
                resource: this.Validation.check(this.Resources.BANNERS),
            },
            {
                name: "md-trash",
                resource: this.Validation.check(this.Resources.BANNERS),
            },
            // { name: "md-arrow-down", resource: true },
            // { name: "md-arrow-up", resource: true },
        ];
        menuIcons = this.menuIconList
            .filter((item) => item.resource)
            .map((item) => item.name);
        //
        editItem(dataItem: Label) {
            this.$router.push({
                path:'/label/edit/'+dataItem.labelId});
        }

        addItem() {
            this.$router.push({
                path:'/label/add'});


        }
        //
        $refs!: {
            sort: HTMLFormElement;
            editSort: HTMLFormElement;
            save: AppButton;
            edit: AppButton;
        };
        //
        // handleSubmit(name) {
        //     this.$refs[name].validate((valid) => {
        //         if (valid) {
        //             this.$Message.success("Success!");
        //         } else {
        //             this.$Message.error("Fail!");
        //         }
        //     });
        // }
        //
        // 删除型号
        toRemoveItem(item) {
            this.bloc.modelPut.labelsortId = item.labelsortId;
            this.modelDelete = true;
            this.bloc.model.labelId = item.labelId;
            this.$Modal.confirm({
                title: "提示",
                content: "确认删除后将无法恢复！还要继续吗？",
                okText: "删除",
                cancelText: "取消",
                onOk: () => {
                    this.bloc
                        .deleteModel(this.bloc.model.labelId)
                        .then((res) => {
                            if (res.name === "") {
                                this.$Message.success("标签删除成功");
                                this.bloc.getLabels(
                                    this.bloc.LabelPage.pageIndex,
                                    this.bloc.LabelPage.pageSize,
                                    "DESC",
                                    this.bloc.sortLabel.labelsortId,
                                    undefined,
                                    this.bloc.model.modelName
                                );
                            } else {
                                this.$Message.error("标签删除失败");
                            }
                        })
                        .catch((res) => {
                            this.$Message.error(res.message);
                        })
                        .finally(() => {});
                },
            });
        }
        //
        modelDele(labelsortId) {
            this.bloc
                .deleteModel(labelsortId)
                .then((res) => {
                    if (res.name === "") {
                        this.$Message.success("标签分类删除成功");
                        this.bloc.getLabels(
                            this.bloc.LabelPage.pageIndex,
                            this.bloc.LabelPage.pageSize,
                            "DESC",
                            this.bloc.sortLabel.labelsortId,
                            undefined,
                            this.bloc.model.modelName
                        );
                    } else {
                        this.$Message.error("设备型号删除失败");
                    }
                })
                .catch((res) => {
                    this.$Message.error(res.message);
                })
                .finally(() => {});
        }
        //
        selectCurrentMenu(val, idx) {
            this.AllSort = false;
            this.bloc.currentIdx = idx;
            this.bloc.sortLabel = val;
            this.bloc.model.labelsortId = val.id;
            this.bloc.getLabels(
                1,
                this.bloc.LabelPage.pageSize,
                "DESC",
                this.bloc.sortLabel.labelsortId,
                undefined,
                this.bloc.model.labelname,
            );
            this.changeRoute();
        }
        //
        handleSort(icon: string, item: LabelSort) {
            if (icon === "md-create") this.handleEdit(item);
            if (icon === "md-trash") {
                this.handleDelete(item);
            }
            if (icon === "md-arrow-down") {
                this.bloc.getAllSort(1, 1000, "ASC").then((res) => {
                    let sortIdS = res.map((item) => {
                        return item.labelsortId;
                    });
                    let index = sortIdS.findIndex((sortId) => {
                        return sortId === item.labelsortId;
                    });
                    if (index < sortIdS.length - 1) {
                        let sortId = sortIdS[index];
                        sortIdS[index] = sortIdS[index + 1];
                        sortIdS[index + 1] = sortId;
                        console.log(sortIdS);
                        this.bloc.putLabelSortSort(sortIdS).then((res) => {
                            this.$Message.success("下移成功");
                            this.initTreeList();
                        });
                    } else {
                        this.$Message.success("已经是最底部了");
                    }
                });
            }
            if (icon === "md-arrow-up") {
                this.bloc.getAllSort(1, 1000, "ASC").then((res) => {
                    let sortIdS = res.map((item) => {
                        return item.labelsortId;
                    });
                    let index = sortIdS.findIndex((sortId) => {
                        return sortId === item.labelsortId;
                    });
                    if (index > 0) {
                        let sortId = sortIdS[index];
                        sortIdS[index] = sortIdS[index - 1];
                        sortIdS[index - 1] = sortId;
                        console.log(sortIdS);
                        this.bloc.putLabelSortSort(sortIdS).then((res) => {
                            this.$Message.success("上移成功");
                            this.initTreeList();
                        });
                    } else {
                        this.$Message.success("已经是最顶部了");
                    }
                });
            }
        }

        // 新增分类方法
        handleAdd(item) {
            this.addLabel = true;
            this.sort.labelsortname = '';
        }
        //
        addSort(labelsortname) {
            this.$refs.sort.validate((valid) => {
                if (valid) {
                    this.$refs.save.bloc.loading = true;
                    this.bloc
                        .addSort(labelsortname)
                        .then((res) => {
                            this.addLabel = false;
                            this.initTreeList();
                            this.$Message.success("新增成功");
                            // this.$refs.save.bloc.loading = false;
                        })
                        .catch((res) => {
                            setTimeout(() => {
                                this.$Message.error("新增失败");
                            }, 1500);
                        })
                        .finally(() => {
                            setTimeout(() => {
                                this.$refs.save.bloc.loading = false;
                            }, 3000);
                        });
                }
            });
        }
        // 编辑分类
        handleEdit(item) {
            this.edit = true;
            this.sort1.id = item.labelsortId;
            this.sort1.labelsortname1 = item.labelsortname;
        }
        //
        editSorts(labelsortId, labelsortname) {
            this.$refs.editSort.validate((valid) => {
                if (valid) {
                    this.$refs.edit.bloc.loading = true;
                    this.bloc
                        .editSort(labelsortId, labelsortname)
                        .then((res) => {
                            this.edit = false;
                            this.$Message.success("编辑标签分类成功");
                            this.initTreeList();
                        })
                        .catch((res) => {
                            setTimeout(() => {
                                this.$Message.error("编辑标签分类失败");
                            }, 1500);
                        })
                        .finally(() => {
                            setTimeout(() => {
                                this.$refs.edit.bloc.loading = false;
                            }, 3000);
                        });
                }
            });
        }
        //
        cancel() {
            this.$refs["sort"].resetFields();
            this.$refs["editSort"].resetFields();
        }
        //
        // 删除分类
        handleDelete(item) {
            this.bloc.model.labelsortId = item.labelsortId;
            this.$Modal.confirm({
                title: "提示",
                content: "确认删除后将无法恢复！还要继续吗？",
                okText: "删除",
                cancelText: "取消",
                onOk: () => {
                    this.bloc
                        .deleteSort(this.bloc.model.labelsortId)
                        .then((res) => {
                            if (res.message !== "SUCCESS") {
                                this.$Message.error("标签分类删除失败");
                            } else {
                                this.$Message.success("标签分类删除成功");
                                this.initTreeList();
                            }
                        })
                        .catch((res) => {
                            this.$Message.error("设备分类删除失败");
                        })
                        .finally(() => {});
                },
            });
        }
        //
        // handleDele(id) {}
        //
        reset() {
            this.bloc.model = {
                companyId: 0,
                labelname: "",
            };
            this.bloc.getLabels(
                this.bloc.LabelPage.pageIndex,
                this.bloc.LabelPage.pageSize,
                "DESC",
                undefined,
                undefined,
                undefined
            );
        }
        changepages(val) {
            this.bloc.getLabels(
                val,
                this.bloc.LabelPage.pageSize,
                "DESC",
                this.bloc.model.labelsortId,
                this.bloc.model.companyId,
                this.bloc.model.labelname
            );
        }
        changepagesize(val) {
            this.bloc.LabelPage.pageSize = val;
            this.bloc.getLabels(
                1,
                this.bloc.LabelPage.pageSize,
                "DESC",
                this.bloc.model.labelsortId,
                this.bloc.model.companyId,
                this.bloc.model.modelName
            );
        }
        //
        initTreeList() {
            this.bloc
                .getAllSort(1, 1000, "ASC")
                .then((res) => {
                    this.changeRoute();
                    this.bloc.model.labelsortId = this.bloc.sortLabel.labelsortId;
                    this.bloc.getLabels(
                        this.bloc.LabelPage.pageIndex,
                        this.bloc.LabelPage.pageSize,
                        "DESC",
                        this.bloc.model.labelsortId,
                        undefined,
                        undefined
                    );
                })
                .finally(() => {});
        }
        //
        changeRoute() {
            this.$router.push({
                path: "/label",
                query: { labelsortId: this.bloc.sortLabel.labelsortId + "" },
            });
        }


        // mounted() {
        //   this.bloc.getDeviceModel(1, 10, 'DESC', undefined)
        //   this.initTreeList()
        //   this.bloc.getCompany(this.bloc.company.pageIndex, this.bloc.company.pageSize, 'DESC')
        //   this.bloc.getAllSort(1, 1000, 'DESC')
        // }
    }
</script>
<style lang="less" scoped>
  .container {
    padding-top: 20px;
    background-color: rgba(255, 255, 255, 1);

    .tree {
      margin-left: 20px;
    }
  }

  .left {
    // min-height: 100%;
    background-color: rgba(255, 255, 255, 1);
    border: 1px solid rgba(242, 242, 242, 1);
    cursor: pointer;
  }

  .left .ivu-col-span-6 {
    display: block;
    margin-right: 60px;
    width: 18%;
    background-color: yellow;
  }

  .fade-enter-active {
    transition: all 0.3s ease;
  }

  .fade-leave-active {
    transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
  }

  .fade-enter,
  .fade-leave-to {
    transform: translateX(10px);
    opacity: 0;
  }

  .category {
    margin-bottom: 20px;
    background-color: rgba(255, 255, 255, 1);
    height: 80px;
    border: 1px solid rgba(242, 242, 242, 1);
    padding: 20px 20px;
  }
  .tree-box {
    max-height: 780px;
    overflow-y: auto;
    border-bottom: 0.5px solid #f2f2f2;
  }
  .tree-menu {
    display: flex;
    align-items: center;
    height: 40px;
    padding: 5px 20px;
    font-size: 14px;
    color: #999;

    label {
      padding: 0 10px 0 5px;
      width: 88px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .right {
    min-height: 600px;
    background-color: rgba(255, 255, 255, 1);
  }

  .head {
    padding-left: 20px;
    padding-top: 20px;
    text-align: left;
    height: 61px;
    border-bottom: 1px solid rgba(242, 242, 242, 1);
  }

  .head span > span {
    padding-top: 2px;
  }

  .ivu-tree {
    height: 100%;
  }

  .active-menu {
    color: #0079fe;
  }

  /deep/ .ivu-tree-arrow > .ivu-icon-ios-arrow-forward:before {
    content: "\f1d0" !important;
  }

  /deep/ .ivu-layout {
    background-color: rgba(255, 255, 255, 1);
  }
</style>
